package com.tbl.modules.wms.service.Impl.businessutils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tbl.common.config.ThreadConfig;
import com.tbl.common.utils.DateUtils;
import com.tbl.modules.wms.constant.EbsInterfaceEnum;
import com.tbl.modules.wms.dao.businessutils.BusinessUtilsDAO;
import com.tbl.modules.wms.entity.interfacelog.InterfaceDo;
import com.tbl.modules.wms.entity.inventory.InventoryRegistration;
import com.tbl.modules.wms.service.businessutils.BusinessUtilsService;
import com.tbl.modules.wms.service.interfacelog.InterfaceDoService;
import com.tbl.modules.wms.service.inventory.InventoryRegistrationService;
import com.tbl.modules.wms.service.webservice.client.WmsService;
import net.sf.json.JSONArray;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * 业务流程公用服务实现
 * @author cxf
 **/
@Service
public class BusinessUtilsServiceImpl extends ServiceImpl<BusinessUtilsDAO, T> implements BusinessUtilsService {

    /**
     * 日志打印
     */
    private final Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 盘点登记服务
     */
    @Autowired
    private InventoryRegistrationService inventoryRegistrationService;
    /**
     * wms接口调用入口
     */
    @Autowired
    private WmsService wmsService;
    /**
     * 接口执行
     */
    @Autowired
    private InterfaceDoService interfaceDoService;
    /**
     * 线程池配置j'o
     */
    @Resource
    private ThreadConfig threadConfig;

    /**
     * 盘点米数审核
     */
    @Override
    public void inventoryMeterBusiness(){
        logger.info("盘点米数审核接口开始！");
        List<InterfaceDo> lstInterfaceDo = interfaceDoService.selectList(new EntityWrapper<InterfaceDo>()
                .eq("INTERFACECODE", EbsInterfaceEnum.FEWMS028)
                //盘点审核米数接口，只对新增的离线接口进行执行，失败的不执行
                .in("ISSUCCESS","0")
                .orderBy("CREATETIME"));
        if (lstInterfaceDo!=null && lstInterfaceDo.size()>0) {
            CountDownLatch countDownLatch = new CountDownLatch(lstInterfaceDo.size());
            for (InterfaceDo interfaceDo : lstInterfaceDo) {
                threadConfig.asyncServiceExecutor().execute(() -> {
                    try {
                        JSONArray jsonArray = JSONArray.fromObject(interfaceDo.getCblogParams());
                        if (jsonArray.size()>0){
                            Map<String, Object> identityHashMap = new IdentityHashMap<>();
                            for(int i=0;i<jsonArray.size();i++) {
                                @SuppressWarnings("unchecked")
                                List<Map<String, Object>> jsonMapList = (List<Map<String, Object>>)
                                        JSON.parse(jsonArray.getJSONObject(i).get("line").toString());
                                if (jsonMapList.size()>0){
                                    Map<String, Object> innerMap;
                                    for (Map map: jsonMapList){
                                        innerMap = new HashMap<>(4);
                                        innerMap.put("check_num", map.get("check_num"));
                                        innerMap.put("zjdh", map.get("zjdh"));
                                        innerMap.put("qty", map.get("qty"));
                                        innerMap.put("pandian_by", map.get("pandian_by"));
                                        identityHashMap.put(new String("line"),innerMap);
                                    }

                                    //盘点米数审核失败的质保号
                                    List<String> failQacodes = wmsService.FEWMS028(identityHashMap, interfaceDo.getQacode(),
                                            interfaceDo.getBatchNo());
                                    InventoryRegistration inventoryRegistrationEntity = new InventoryRegistration();
                                    /*if (failQacodes.size()==0){*/
                                    //全部成功
                                    inventoryRegistrationEntity.setState(1L);
                                    inventoryRegistrationService.update(inventoryRegistrationEntity,
                                            new EntityWrapper<InventoryRegistration>()
                                                    .eq("EXAMINED",interfaceDo.getSpesign())
                                                    .isNotNull("EDITMETER"));
                                    /*}else {
                                        //修改盘点登记表的米数审核状态:成功部分
                                        inventoryRegistrationEntity.setState(1L);
                                        inventoryRegistrationService.update(inventoryRegistrationEntity,
                                                new EntityWrapper<InventoryRegistration>()
                                                .eq("EXAMINED",interfaceDo.getSpesign())
                                                .notIn("QACODE",failQacodes));
                                        //修改盘点登记表的米数审核状态:失败部分
                                        inventoryRegistrationEntity.setState(0L);
                                        inventoryRegistrationService.update(inventoryRegistrationEntity,
                                                new EntityWrapper<InventoryRegistration>()
                                                .eq("EXAMINED",interfaceDo.getSpesign())
                                                .in("QACODE",failQacodes));
                                    }

                                    try{
                                        //找出这个集结号下的所有上传米数盘点的数据中执行成功的,来对盘点登记表进行更新
                                        inventoryRegistrationService.updateInventoryMeter(interfaceDo.getSpesign(), failQacodes);
                                        //找出这个集结号下的所有上传米数盘点的数据中执行成功的,来对库存表进行更新（这里要保证库存表中质保号没有重复数据）
                                        storageInfoService.updateStorageInfoMeterByInventoryRegistration(interfaceDo.getSpesign(), failQacodes);
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }*/

                                    /*interfaceDo.setIssuccess(failQacodes.size() == 0 ? "1" : "2");*/
                                    interfaceDo.setIssuccess("1");
                                    interfaceDo.setOperatetime(DateUtils.getTime());
                                    interfaceDo.setExecutenum(interfaceDo.getExecutenum() + 1);
                                    interfaceDoService.updateById(interfaceDo);
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        // 这个不管是否异常都需要数量减,否则会被堵塞无法结束
                        countDownLatch.countDown();
                    }
                });
            }
            try {
                countDownLatch.await();
                logger.info("所有线程结束");
            } catch (Exception e) {
                logger.error("阻塞异常");
            }
        }
    }
}
